using JTZY.Admin.WebApi.Filters;
using JTZY.Infrastructure.Enums;
using JTZY.Model;
using JTZY.Model.Order;
using JTZY.Model.Order.Dto;
using JTZY.Repository;
using JTZY.Service.Order;
using JTZY.Service.Order.IOrderService;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using static JTZY.Common.GlobalEnumVars;

//创建时间：2024-11-12
namespace JTZY.Admin.WebApi.Controllers.Order
{
    /// <summary>
    /// 退货单表
    /// </summary>
    [Verify]
    [Route("order/Corecmsbillaftersales")]
    public class CorecmsbillaftersalesController : BaseController
    {
        /// <summary>
        /// 退货单表接口
        /// </summary>
        private readonly ICorecmsbillaftersalesService _CorecmsbillaftersalesService;
        private readonly IRedisOperationRepository _redisOperationRepository;

        public CorecmsbillaftersalesController(ICorecmsbillaftersalesService CorecmsbillaftersalesService,IRedisOperationRepository redisOperationRepository)
        {
            _CorecmsbillaftersalesService = CorecmsbillaftersalesService;
            _redisOperationRepository = redisOperationRepository;
        }

        /// <summary>
        /// 查询退货单表列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpGet("list")]
        [ActionPermissionFilter(Permission = "corecmsbillaftersales:list")]
        public IActionResult QueryCorecmsbillaftersales([FromQuery] CorecmsbillaftersalesQueryDto parm)
        {
            parm.userId = HttpContext.GetUId();
            var response = _CorecmsbillaftersalesService.GetList(parm);
            return SUCCESS(response);
        }

        [HttpGet("afterstocklist")]
        [ActionPermissionFilter(Permission = "corecmsbillaftersales:list")]
        public IActionResult QueryAfterStockList([FromQuery] AfterStockQueryDto parm)
        {
            parm.userId = HttpContext.GetUId();
            var response = _CorecmsbillaftersalesService.GetAfterStockList(parm);
            return SUCCESS(response);
        }

        /// <summary>
        /// 查询退货单表详情
        /// </summary>
        /// <param name="AftersalesId"></param>
        /// <returns></returns>
        [HttpGet("{AftersalesId}")]
        [ActionPermissionFilter(Permission = "corecmsbillaftersales:query")]
        public IActionResult GetCorecmsbillaftersales(string AftersalesId)
        {
            var response = _CorecmsbillaftersalesService.GetInfo(AftersalesId);

            var info = response.Adapt<CorecmsbillaftersalesDto>();
            return SUCCESS(info);
        }

        /// <summary>
        /// 导出退货单表
        /// </summary>
        /// <returns></returns>
        [Log(Title = "退货单表", BusinessType = BusinessType.EXPORT, IsSaveResponseData = false)]
        [HttpGet("export")]
        [ActionPermissionFilter(Permission = "corecmsbillaftersales:export")]
        public IActionResult Export([FromQuery] CorecmsbillaftersalesQueryDto parm)
        {
            parm.PageNum = 1;
            parm.PageSize = 100000;
            parm.userId = HttpContext.GetUId();

            var list = _CorecmsbillaftersalesService.ExportList(parm).Result;
            if (list == null || list.Count <= 0)
            {
                return ToResponse(ResultCode.FAIL, "没有要导出的数据");
            }
            var result = ExportExcelMini(list, "退货单表", "退货单表");
            return ExportExcel(result.Item2, result.Item1);
        }

        [HttpPost("addaftersales")]
        [ActionPermissionFilter(Permission = "corecmsbillaftersales:add")]
        public async Task<IActionResult> AddAftersales([FromBody] ToAddBillAfterSalesPost entity)
        {
            var jm = new WebApiCallBack();

            jm.otherData = entity;
            if (string.IsNullOrEmpty(entity.orderId))
            {
                //jm.msg = "请输入订单编号";
                //jm.code = 13100;
                return ToResponse(ResultCode.FAIL, "请输入订单编号");
            }
            if (entity.type == 0)
            {
                //jm.msg = "缺少参数，请确认";
                //jm.code = 10051;
                return ToResponse(ResultCode.FAIL, "缺少参数，请确认");
            }
            string[] imgs = !string.IsNullOrEmpty(entity.images) ? entity.images.Split(',') : null;
            jm = await _CorecmsbillaftersalesService.ToAdd(entity.userId, entity.orderId, entity.type, entity.items, imgs,
                entity.reason, entity.refund, entity.sourceType,entity.reMethod,entity.retReasons);
            jm.otherData = entity;
            if (jm.status)
            {
                return SUCCESS(jm.data);

            }
            else
            {
                return ToResponse(ResultCode.FAIL, jm.msg);

            }

        }

        /// <summary>
        /// 代理滞销退货申请
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost("addunsalableaftersales")]
        [ActionPermissionFilter(Permission = "corecmsbillaftersales:add")]
        public async Task<IActionResult> AddUnsalableAftersales([FromBody] ToAddUnsaleAfterSalesPost entity)
        {
            var jm = new WebApiCallBack();

            jm.otherData = entity;

            if (entity.type == 0)
            {
                //jm.msg = "缺少参数，请确认";
                //jm.code = 10051;
                return ToResponse(ResultCode.FAIL, "缺少参数，请确认");
            }

            entity.userId=HttpContext.GetUId();
            string[] imgs = !string.IsNullOrEmpty(entity.images) ? entity.images.Split(',') : null;
            jm = await _CorecmsbillaftersalesService.ToAddUn(entity.userId, entity.type, entity.items, imgs,
                entity.reason, entity.refund, entity.sourceType,entity.details);
            jm.otherData = entity;
            if (jm.status)
            {
                return SUCCESS(jm.data);

            }
            else
            {
                return ToResponse(ResultCode.FAIL, jm.msg);

            }

        }


        //[HttpPost("addafterunsalable")]
        //[ActionPermissionFilter(Permission = "corecmsbillaftersales:add")]
        //public async Task<IActionResult> AddAfterun([FromBody] ToAddBillAfterSalesPost entity)
        //{
        //    var jm = new WebApiCallBack();

        //    jm.otherData = entity;

        //    if (entity.type == 0)
        //    {
        //        return ToResponse(ResultCode.FAIL, "缺少参数，请确认");
        //    }
        //    string[] imgs = !string.IsNullOrEmpty(entity.images) ? entity.images.Split(',') : null;
        //    jm = await _CorecmsbillaftersalesService.ToAddUn(entity.userId, entity.orderId, entity.type, entity.items, imgs,
        //        entity.reason, entity.refund, entity.sourceType, entity.reMethod, entity.retReasons);
        //    jm.otherData = entity;
        //    if (jm.status)
        //    {
        //        return SUCCESS(jm.data);

        //    }
        //    else
        //    {
        //        return ToResponse(ResultCode.FAIL, jm.msg);

        //    }

        //}

        [HttpPost("audit")]
        [ActionPermissionFilter(Permission = "corecmsbillaftersales:query")]
        public async Task<IActionResult> AuditAftersales([FromBody] ToAddBillAfterSalesPost entity)
        {
            var jm = new WebApiCallBack();

            jm.otherData = entity;
            if (string.IsNullOrEmpty(entity.AftersalesId))
            {
                //jm.msg = "请输入订单编号";
                //jm.code = 13100;
                return ToResponse(ResultCode.FAIL, "请输入订单编号");
            }

            string[] imgs = !string.IsNullOrEmpty(entity.images) ? entity.images.Split(',') : null;
            jm = await _CorecmsbillaftersalesService.Audit(entity.AftersalesId, (int)BillAftersalesStatus.Success, 2, 
                 entity.refundAmount, "", null);
 
            jm.data = entity;
            if (jm.status)
            {
                return SUCCESS(jm.data);

            }
            else
            {
                return ToResponse(ResultCode.FAIL, jm.msg);

            }

        }

        [HttpPost("cancel")]
        [ActionPermissionFilter(Permission = "corecmsbillaftersales:query")]

        public async Task<IActionResult> CancelAfterSales([FromBody] ToAddBillAfterSalesPost entity) 
        {
            var jm = new WebApiCallBack();
            if (string.IsNullOrEmpty(entity.AftersalesId))
            {
                //jm.msg = "请输入订单编号";
                //jm.code = 13100;
                return ToResponse(ResultCode.FAIL, "请输入订单编号");
            }
            jm = _CorecmsbillaftersalesService.CancelAfterSales(new Corecmsbillaftersales { AftersalesId = entity.AftersalesId});

            if (jm.status)
            {
                return SUCCESS(jm.data);

            }
            else
            {
                return ToResponse(ResultCode.FAIL, jm.msg);

            }
        }

        [HttpPost("noaudit")]
        [ActionPermissionFilter(Permission = "corecmsbillaftersales:query")]
        public async Task<IActionResult> NoAuditAfterSales([FromBody] ToAddBillAfterSalesPost entity)
        {
            var jm = new WebApiCallBack();
            if (string.IsNullOrEmpty(entity.AftersalesId))
            {
                //jm.msg = "请输入订单编号";
                //jm.code = 13100;
                return ToResponse(ResultCode.FAIL, "请输入订单编号");
            }
            if (string.IsNullOrEmpty(entity.Mark))
            {
                //jm.msg = "缺少参数，请确认";
                //jm.code = 10051;
                return ToResponse(ResultCode.FAIL, "请填写拒绝理由");
            }
            jm = _CorecmsbillaftersalesService.NoAuditAfterSales(new Corecmsbillaftersales { AftersalesId = entity.AftersalesId, Mark = entity.Mark });

            if (jm.status)
            {
                return SUCCESS(jm.data);

            }
            else
            {
                return ToResponse(ResultCode.FAIL, jm.msg);

            }
        }

        [HttpPost("take")]
        [ActionPermissionFilter(Permission = "corecmsorder:edit")]
        [Log(Title = "订单状态修改", BusinessType = BusinessType.UPDATE)]
        public async Task<IActionResult> Take([FromBody] CorecmsbillaftersalesDto parm)
        {
            var userId = HttpContext.GetUId();
            var modal = parm.Adapt<Corecmsbillaftersales>().ToUpdate(HttpContext);
            var lockKey = "LOCK_TakeOrder:AftersalesId_" + modal.AftersalesId;
            var lockHolder = Guid.NewGuid().ToString("N"); //锁持有者
            var redisUserLock = _redisOperationRepository.LockTake(lockKey, lockHolder, TimeSpan.FromSeconds(10));
            if (redisUserLock)
            {
                var jm = await _CorecmsbillaftersalesService.Take(modal, userId);

                if (jm.status)
                {
                    return SUCCESS(parm);

                }
                else
                {
                    return ToResponse(ResultCode.FAIL, jm.msg);

                }
            }
            else 
            {
                return ToResponse(ResultCode.FAIL, "当前请求太频繁_请稍后再试");

            }
        }

        [HttpPost("refund")]
        [ActionPermissionFilter(Permission = "corecmsorder:edit")]
        [Log(Title = "订单状态修改", BusinessType = BusinessType.UPDATE)]
        public async Task<IActionResult> Refund([FromBody] CorecmsbillaftersalesDto parm)
        {
            var userId = HttpContext.GetUId();
            var modal = parm.Adapt<Corecmsbillaftersales>().ToUpdate(HttpContext);
            var lockKey = "LOCK_TakeOrder:AftersalesId_" + modal.AftersalesId;
            var lockHolder = Guid.NewGuid().ToString("N"); //锁持有者
            var redisUserLock = _redisOperationRepository.LockTake(lockKey, lockHolder, TimeSpan.FromSeconds(10));
            if (redisUserLock)
            {
                var jm = await _CorecmsbillaftersalesService.Refund(modal, userId);

            if (jm.status)
            {
                return SUCCESS(parm);

            }
            else
            {
                return ToResponse(ResultCode.FAIL, jm.msg);

                }
            }
            else
            {
                return ToResponse(ResultCode.FAIL, "当前请求太频繁_请稍后再试");

            }
        }

        [HttpPost("ship")]
        [ActionPermissionFilter(Permission = "corecmsorder:edit")]
        [Log(Title = "订单状态修改", BusinessType = BusinessType.UPDATE)]
        public async Task<IActionResult> Ship([FromBody] CorecmsbillaftersalesDto parm)
        {
            var userId = HttpContext.GetUId();
            var modal = parm.Adapt<Corecmsbillaftersales>().ToUpdate(HttpContext);
            var lockKey = "LOCK_TakeOrder:AftersalesId_" + modal.AftersalesId;
            var lockHolder = Guid.NewGuid().ToString("N"); //锁持有者
            var redisUserLock = _redisOperationRepository.LockTake(lockKey, lockHolder, TimeSpan.FromSeconds(10));
            if (redisUserLock)
            {
                var response = await _CorecmsbillaftersalesService.Ship(modal, userId);
            if (response.status)
            {
                return SUCCESS(response.data);

            }
            else
            {
                return ToResponse(ResultCode.FAIL, response.msg);
                }
            }
            else
            {
                return ToResponse(ResultCode.FAIL, "当前请求太频繁_请稍后再试");

            }
            //return ToResponse(response);
        }

        [HttpPost("pack")]
        [ActionPermissionFilter(Permission = "corecmsorder:edit")]
        [Log(Title = "商家发货", BusinessType = BusinessType.UPDATE)]
        public IActionResult Pack([FromBody] OrderPackDto parm)
        {
            //var modal = parm.Adapt<Corecmsorder>().ToUpdate(HttpContext);
            parm.userId = HttpContext.GetUId();
            var response = _CorecmsbillaftersalesService.Pack(parm);
            if (response.status)
            {
                return SUCCESS(response.data);

            }
            else
            {
                return ToResponse(ResultCode.FAIL, response.msg);
            }
        }


        [HttpGet("rePrintOrder")]
        [ActionPermissionFilter(Permission = "corecmsorderitem:query")]
        public async Task<IActionResult> RePrintOrder(string orderId)
        {
            long userId = HttpContext.GetUId();
            var response = _CorecmsbillaftersalesService.GetInfo(orderId);
            await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.AfterSaleOrderPrint, JsonConvert.SerializeObject(response));
            var info = response.Adapt<List<CorecmsbillaftersalesDto>>();
            return SUCCESS(info);
        }
    }
}